﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ExtensionMethods.cs" company="TomCorp">
//   Tom
// </copyright>
// <summary>
//   Defines the ExtensionMethods type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace GeoCoder.ExtensionMethods {
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows;

    /// <summary>
    /// The extension methods.
    /// </summary>
    public static class ExtensionMethods {
        /// <summary>
        /// The find descendants.
        /// </summary>
        /// <param name="parent">
        /// The parent.
        /// </param>
        /// <param name="predicate">
        /// The predicate.
        /// </param>
        /// <param name="deepSearch">
        /// The deep search.
        /// </param>
        /// <typeparam name="T">
        /// A Type
        /// </typeparam>
        /// <returns>
        /// The <see cref="IEnumerable"/>.
        /// </returns>
        public static IEnumerable<T> FindDescendants<T>(this DependencyObject parent, Func<T, bool> predicate, bool deepSearch = false) where T : DependencyObject {
            var children = LogicalTreeHelper.GetChildren(parent).OfType<DependencyObject>().ToList();

            foreach (var child in children) {
                var typedChild = child as T;
                if ((typedChild != null) && (predicate == null || predicate.Invoke(typedChild))) {
                    yield return typedChild;
                    if (deepSearch) foreach (var foundDescendant in FindDescendants(child, predicate, true)) yield return foundDescendant;
                } else {
                    foreach (var foundDescendant in FindDescendants(child, predicate, deepSearch)) yield return foundDescendant;
                }
            }
        }

        /// <summary>
        /// Converts a given date to a unix time stamp.
        /// </summary>
        /// <param name="dateTime">
        /// The date.
        /// </param>
        /// <returns>
        /// The number of seconds since 1/1/1970<see cref="double"/>.
        /// </returns>
        public static double ToUnixTimeStamp(this DateTime dateTime) {
            return (dateTime - new DateTime(1970, 1, 1).ToLocalTime()).TotalSeconds;
        }
    }
}
